package com.main.usermanagement.domain.user.event.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.main.common.utils.exceptions.StackTraceLog;
import com.main.crossdomaineventmanagement.event.core.EventPublisher;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import com.main.usermanagement.domain.user.event.payload.RegisterSuccessPayload;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.main.common.enums.MessageType.CLIENT;

@Service
@Slf4j
@RocketMQMessageListener(
        topic = "TransactionEventsTopic",
        consumerGroup = "RegisterConsumerGroup",
        selectorType = SelectorType.TAG,
        selectorExpression = "REGISTER_SUCCESS"
)
public class RegisterSuccessHandler implements RocketMQListener<MessageExt> {

    private final StackTraceLog stackTraceLog = new StackTraceLog();
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());  // 仅注册 JavaTime 模块

    @Autowired
    @Qualifier("rocketMQEventPublisher")
    private EventPublisher eventPublisher;

    public void handleRegisterSuccessEvent(String payload) {
        RegisterSuccessPayload registerSuccessPayload = null;
        try {
            // 反序列化 payload 为业务对象
            registerSuccessPayload = objectMapper.readValue(payload, RegisterSuccessPayload.class);
            //发送通知
            String number = registerSuccessPayload.getNumber();
            String password = registerSuccessPayload.getPassword();
            log.info("RegisterSuccessEvent: number = {}, password = {}", number, password);
            sendMessage(registerSuccessPayload);
        } catch (JsonProcessingException e) {
            System.err.println("反序列化 payload 失败: " + e.getMessage());
        }
    }

    public void sendMessage(RegisterSuccessPayload registerSuccessPayload) throws JsonProcessingException {
        Map<String, Object> payload = new HashMap<>();
        payload.put("payload", registerSuccessPayload);
        payload.put("type", CLIENT);
        payload.put("userId", "");
        payload.put("clientId", registerSuccessPayload.getClientId());
        payload.put("groupId", "");
        payload.put("category", "REGISTER");
        payload.put("routeKey", "register");
        String payloadJson = new ObjectMapper().writeValueAsString(payload);
        EventMessage event = new EventMessage("WEBSOCKET_MSG",  "REGISTER", payloadJson);
        eventPublisher.publish(event);
    }

    @Override
    public void onMessage(MessageExt msg) {
        try {
            EventMessage event = objectMapper.readValue(msg.getBody(), EventMessage.class);
            log.info("收到账号创建成功消息，原始内容: {}", event.getPayload());
            handleRegisterSuccessEvent(event.getPayload());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
